import { ref, computed } from 'vue'
import { ctpService } from '@/services/ctpService'

/**
 * 个人持仓数据管理 Composable
 * 负责查询、计算和实时更新个人持仓量数据
 */
export function usePositionData() {
  // 持仓数据状态
  const positionData = ref([])
  const isLoading = ref(false)
  const lastUpdateTime = ref(null)
  const error = ref(null)

  // 多头和空头持仓总量（改为ref，用于增量更新）
  const longPosition = ref(0)
  const shortPosition = ref(0)

  // 净持仓量（多头 - 空头）
  const netPosition = computed(() => {
    return longPosition.value + shortPosition.value // shortPosition已经是负数
  })

  // 持仓盈亏总计
  const totalPositionProfit = computed(() => {
    return positionData.value.reduce((total, pos) => total + (pos.position_profit || 0), 0)
  })

  /**
   * 查询持仓数据
   * @param {string} contractCode - 可选的合约代码，如果提供则只查询该合约的持仓
   */
  const queryPositionData = async (contractCode = null) => {
    if (isLoading.value) {
      return
    }

    isLoading.value = true
    error.value = null

    try {
      const result = await ctpService.queryPosition()

      if (result.success) {
        const positions = result.data || []

        // 如果指定了合约代码，只保留该合约的持仓
        if (contractCode) {
          positionData.value = positions.filter(pos => pos.instrument_id === contractCode)
        } else {
          positionData.value = positions
        }
        // 按合约和方向合并持仓数据
        const mergedPositions = new Map()
        positions.forEach((pos, index) => {
          const key = `${pos.instrument_id}_${pos.posi_direction}`

          if (mergedPositions.has(key)) {
            // 合并同一合约同一方向的持仓
            const existing = mergedPositions.get(key)
            existing.position += pos.position
            existing.today_position += pos.today_position
            existing.yd_position += pos.yd_position
            existing.position_profit += pos.position_profit
          } else {
            // 新的持仓记录
            mergedPositions.set(key, {
              ...pos,
              position: pos.position,
              today_position: pos.today_position,
              yd_position: pos.yd_position,
              position_profit: pos.position_profit
            })
          }
        })

        // 更新positionData为合并后的数据
        positionData.value = Array.from(mergedPositions.values())
        let initialLong = 0;
        let initialShort = 0;
        positionData.value.forEach((pos, index) => {
          if (pos.posi_direction === '2') {
            initialLong += pos.position;
          } else if (pos.posi_direction === '3') {
            initialShort += pos.position;
          }
        });

        longPosition.value = initialLong;
        shortPosition.value = -initialShort;

        lastUpdateTime.value = new Date();

        return { success: true, data: positionData.value };
      } else {
        error.value = result.error || '持仓查询失败'
        return { success: false, error: error.value }
      }
    } catch (err) {
      error.value = err.message || '持仓查询异常'
      return { success: false, error: error.value }
    } finally {
      isLoading.value = false
    }
  }

    /**
   * 增量更新持仓 - 支持吃多跑空/吃空跑多策略
   * @param {'buy' | 'sell'} direction - 成交方向
   * @param {number} quantity - 成交数量
   * @param {boolean} isClosing - 是否为平仓
   */
  const incrementallyUpdatePosition = (direction, quantity, isClosing) => {
    const currentLongPosition = longPosition.value;
    const currentShortPosition = Math.abs(shortPosition.value);
    if (isClosing) {
      // 平仓逻辑
      if (direction === 'buy') {
        // 买入平空仓：减少空头持仓（shortPosition是负数，所以加quantity）
        shortPosition.value += quantity;
      } else {
        // 卖出平多仓：减少多头持仓
        longPosition.value -= quantity;
      }
    } else {
      // 开仓逻辑
      if (direction === 'buy') {
        // 买入开多仓：增加多头持仓
        longPosition.value += quantity;
      } else {
        // 卖出开空仓：增加空头持仓（shortPosition是负数，所以减quantity）
        shortPosition.value -= quantity;
      }
    }
  };

  /**
   * 处理交易成交事件，触发持仓数据增量更新
   * @param {Object} tradeData - 成交数据
   * @param {boolean} isClosing - 是否为平仓单
   */
  const handleTradeNotification = async (tradeData, isClosing) => {
    const direction = tradeData.direction === '0' ? 'buy' : 'sell';
    const quantity = tradeData.volume;
    incrementallyUpdatePosition(direction, quantity, isClosing);
  };

  /**
   * 重置持仓数据
   */
  const resetPositionData = () => {
    positionData.value = []
    error.value = null
    lastUpdateTime.value = null;
  }

  /**
   * 获取指定合约的持仓信息
   * @param {string} contractCode - 合约代码
   */
  const getContractPosition = (contractCode) => {
    return positionData.value.filter(pos => pos.instrument_id === contractCode)
  }

  return {
    incrementallyUpdatePosition,
    // 状态
    positionData,
    isLoading,
    lastUpdateTime,
    error,

    // 计算属性
    longPosition,      // 多头持仓（正数，蓝色显示）
    shortPosition,     // 空头持仓（负数，红色显示）
    netPosition,       // 净持仓
    totalPositionProfit, // 总持仓盈亏

    // 方法
    queryPositionData,
    handleTradeNotification,
    resetPositionData,
    getContractPosition
  }
}
